String Searches

Counting substrings

This utility counts the occurrences of a given substring.

// Count Occurances of a Substring
function count(aString, aSubstring)
{
  // initialize counter and offset
  var count = 0
  var offset = 0
  var where = 0
  var tmp = ""+aString

  // search until no more found
  while ((offset < tmp.length) &&
  		 ((where = tmp.indexOf(aSubstring, offset)) >= 0))
  {
  	count++
  	offset = where+aSubstring.length
  }

  // return it	
  return count
}
Copyright ©1998 by Charles River Media, All Rights Reserved